#!/bin/bash
set -e;
echo "get latest version"
source ../../pi.vars;
version=`get_github_latest https://github.com/haiwen/seafile-rpi/releases/latest`


whoname=`whoami`;

if [ -f "/opt/seafile-server/stop.sh" ];then
    /opt/seafile-server/stop.sh||echo 'stop ok !'
fi;
sudo apt-get install sqlite3;
sudo mkdir  -p /opt/seafile-server/export;sudo chmod -R 755 /opt/seafile-server;
sudo chown -R ${whoname} /opt/seafile-server;
rm -rf /opt/seafile-server/seafile-server-${version}* /opt/seafile-server/seafile-server-latest;
curl -k -L  ${github_proxy}/https://github.com/haiwen/seafile-rpi/releases/download/v${version}/seafile-server-${version}-bullseye-arm64v8l.tar.gz --output /opt/seafile-server/seafile-server-${version}.tar.gz
tar -xf /opt/seafile-server/seafile-server-${version}.tar.gz -C /opt/seafile-server/;

cp *.sh /opt/seafile-server/;
sudo pip install -U Pillow==9.3.0 -t /opt/seafile-server/seafile-server-${version}/seahub/thirdpart/;


sed -i "s/User=.*/User=${whoname}/g" seafile.service;
sudo cp seafile.service /lib/systemd/system/;
sudo systemctl daemon-reload;


chmod -R 755 /opt/seafile-server;

if [ -d "/opt/seafile-server/conf" ];then
echo "skip init"
ln -s /opt/seafile-server/seafile-server-${version} /opt/seafile-server/seafile-server-latest;

else
echo "init config"
cd /opt/seafile-server/seafile-server-${version};
./setup-seafile.sh;


sed -i 's/bind = "127.0.0.1/bind = "0.0.0.0/g'  /opt/seafile-server/conf/gunicorn.conf.py

fi;

echo "start seafile-server services......";
sudo systemctl start seafile;



